<!DOCTYPE html>
<html class="client-nojs vector-feature-night-mode-disabled vector-feature-language-in-header-enabled vector-feature-language-in-main-page-header-disabled vector-feature-page-tools-pinned-disabled vector-feature-toc-pinned-clientpref-1 vector-feature-main-menu-pinned-disabled vector-feature-limited-width-clientpref-1 vector-feature-limited-width-content-enabled vector-feature-custom-font-size-clientpref-1 vector-feature-appearance-pinned-clientpref-1 vector-sticky-header-enabled" lang="en" dir="ltr"><head>
<meta charset="UTF-8">
<title>Const (computer programming)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="https://en.wikipedia.org/wiki/Const_(computer_programming)"> <link href="./mw/ext.cite.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/ext.pygments.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.icons.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.search.codex.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/user.styles.css" rel="stylesheet" type="text/css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" type="text/css" href="./mw/site.styles.css">
<link rel="stylesheet" type="text/css" href="./mw/noscript.css">
<link rel="stylesheet" type="text/css" href="./footer.css">
<link rel="stylesheet" type="text/css" href="./vector-2022.css">
</head>
<body class="skin--responsive skin-vector skin-vector-search-vue mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-Const_computer_programming rootpage-Const_computer_programming skin-vector-2022 action-view">
<div class="mw-page-container">
<div class="mw-page-container-inner">
<div class="mw-content-container">
<main id="content" class="mw-body">
<header class="mw-body-header vector-page-titlebar">
<h1 id="firstHeading" class="firstHeading mw-first-heading">
<span id="openzim-page-title" class="mw-page-title-main">const (computer programming)</span>
</h1>
</header>
<a id="top"></a>
<div id="bodyContent" class="vector-body ve-init-mw-desktopArticleTarget-targetContainer" aria-labelledby="firstHeading" data-mw-ve-target-container="">
<div id="mw-content-text" class="mw-body-content mw-content-ltr" lang="en" dir="ltr"><div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr">
<p class="mw-empty-elt">
</p><p>In some <a href="Programming_language" title="Programming language">programming languages</a>, <b>const</b> is a <a href="Type_qualifier" title="Type qualifier">type qualifier</a> (a <a href="Keyword_(computer_programming)" class="mw-redirect" title="Keyword (computer programming)">keyword</a> applied to a <a href="Data_type" title="Data type">data type</a>) that indicates that the data is read-only. While this can be used to declare <a href="Constant_(computer_programming)" title="Constant (computer programming)">constants</a>, <style data-mw-deduplicate="TemplateStyles:r886049734">
/* start https://en.wikipedia.org/ */
.mw-parser-output .monospaced{font-family:monospace,monospace}
/* end https://en.wikipedia.org/ */
</style><span class="monospaced">const</span> in the <a href="List_of_C-family_programming_languages" title="List of C-family programming languages">C family</a> of languages differs from similar constructs in other languages in that it is part of the <i>type</i>, and thus has complicated behavior when combined with <a href="Pointer_(computer_programming)" title="Pointer (computer programming)">pointers</a>, references, <a href="Composite_data_type" title="Composite data type">composite data types</a>, and <a href="Type-checking" class="mw-redirect" title="Type-checking">type-checking</a>. In other languages, the data is not in a single <a href="Memory_location" class="mw-redirect" title="Memory location">memory location</a>, but copied at <a href="Compile_time" title="Compile time">compile time</a> for each use.<sup id="cite_ref-1" class="reference"><a href="#cite_note-1"><span class="cite-bracket">[</span>1<span class="cite-bracket">]</span></a></sup> Languages which use it include <a href="C_(programming_language)" title="C (programming language)">C</a>, <a href="C%2B%2B" title="C++">C++</a>, <a href="D_(programming_language)" title="D (programming language)">D</a>, <a href="JavaScript" title="JavaScript">JavaScript</a>, <a href="Julia_(programming_language)" title="Julia (programming language)">Julia</a>, and <a href="Rust_(programming_language)" title="Rust (programming language)">Rust</a>.
</p>
<meta property="mw:PageProp/toc">
<div class="mw-heading mw-heading2"><h2 id="Introduction">Introduction</h2></div>
<p>When applied in an <a href="Object_(computer_science)" title="Object (computer science)">object</a> <a href="Declaration_(computer_programming)" title="Declaration (computer programming)">declaration</a>,<sup id="cite_ref-2" class="reference"><a href="#cite_note-2"><span class="cite-bracket">[</span>a<span class="cite-bracket">]</span></a></sup> it indicates that the object is a <a href="Constant_(computer_programming)" title="Constant (computer programming)">constant</a>: its <a href="Value_(computer_science)" title="Value (computer science)">value</a> may not be changed, unlike a <a href="Variable_(computer_science)" title="Variable (computer science)">variable</a>. This basic use – to declare constants – has parallels in many other languages.
</p><p>However, unlike in other languages, in the C family of languages the <code>const</code> is part of the <i>type</i>, not part of the <i>object</i>. For example, in C, <code class="mw-highlight mw-highlight-lang-c mw-content-ltr" style="" dir="ltr"><span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">1</span><span class="p">;</span></code> declares an object <code>x</code> of <code>int const</code> type – the <code>const</code> is part of the type, as if it were parsed "(int const) x" – while in <a href="Ada_(programming_language)" title="Ada (programming language)">Ada</a>, <code class="mw-highlight mw-highlight-lang-ada mw-content-ltr" style="" dir="ltr"><span class="no">X</span> <span class="p">:</span> <span class="kr">constant</span> <span class="kt">INTEGER</span> <span class="p">:=</span> <span class="mi">1_</span></code> declares a constant (a kind of object) <code>X</code> of <code>INTEGER</code> type: the <code>constant</code> is part of the <i>object</i>, but not part of the <i>type</i>.
</p><p>This has two subtle results. Firstly, <code>const</code> can be applied to parts of a more complex type – for example, <code>int const * const x;</code> declares a constant pointer to a constant integer, while <code>int const * x;</code> declares a variable pointer to a constant integer, and <code>int * const x;</code> declares a constant pointer to a variable integer. Secondly, because <code>const</code> is part of the type, it must match as part of type-checking. For example, the following code is invalid:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">void</span><span class="w"> </span><span class="nf">f</span><span class="p">(</span><span class="kt">int</span><span class="o">&</span><span class="w"> </span><span class="n">x</span><span class="p">);</span>
<span class="c1">// ...</span>
<span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="n">i</span><span class="p">;</span>
<span class="n">f</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
</pre></div>
<p>because the argument to <code>f</code> must be a <i>variable</i> integer, but <code>i</code> is a <i>constant</i> integer. This matching is a form of <a href="Program_correctness" class="mw-redirect" title="Program correctness">program correctness</a>, and is known as <b>const-correctness</b>. This allows a form of <a href="Programming_by_contract" class="mw-redirect" title="Programming by contract">programming by contract</a>, where functions specify as part of their <a href="Type_signature" title="Type signature">type signature</a> whether they modify their arguments or not, and whether their <a href="Return_value" class="mw-redirect" title="Return value">return value</a> is modifiable or not. This type-checking is primarily of interest in pointers and references – not basic value types like integers – but also for <a href="Composite_data_type" title="Composite data type">composite data types</a> or templated types such as <a href="Container_(abstract_data_type)" title="Container (abstract data type)">containers</a>. It is concealed by the fact that the <code>const</code> can often be omitted, due to <a href="Type_coercion" class="mw-redirect" title="Type coercion">type coercion</a> (implicit <a href="Type_conversion" title="Type conversion">type conversion</a>) and C being <a href="Call-by-value" class="mw-redirect" title="Call-by-value">call-by-value</a> (C++ and D are either call-by-value or call-by-reference).
</p>
<div class="mw-heading mw-heading2"><h2 id="Consequences">Consequences</h2></div>
<p>The idea of const-ness does not imply that the variable as it is stored in <a href="Computer_memory" title="Computer memory">computer memory</a> is unwritable. Rather, <code>const</code>-ness is a <a href="Compile-time" class="mw-redirect" title="Compile-time">compile-time</a> construct that indicates what a programmer <i>should</i> do, not necessarily what they <i>can</i> do. Note, however, that in the case of predefined data (such as <code>char const *</code> <a href="String_literal" title="String literal">string literals</a>), C <code>const</code> is <i>often</i> unwritable.
</p>
<div class="mw-heading mw-heading2"><h2 id="Distinction_from_constants">Distinction from constants</h2></div>
<p>While a constant does not change its value while the program is running, an object declared <code>const</code> may indeed change its value while the program is running. A common example are read only registers within embedded systems like the current state of a digital input. The data registers for digital inputs are often declared as <code>const</code> and <code><a href="Volatile_(computer_programming)" title="Volatile (computer programming)">volatile</a></code>. The content of these registers may change without the program doing anything (<code>volatile</code>) but it would be ill-formed for the program to attempt write to them (<code>const</code>).
</p>
<div class="mw-heading mw-heading2"><h2 id="Other_uses">Other uses</h2></div>
<p>In addition, a (non-static) member-function can be declared as <code>const</code>. In this case, the <a href="This_(computer_programming)" title="This (computer programming)"><code>this</code> pointer</a> inside such a function is of type <code>object_type const *</code> rather than merely of type <code>object_type *</code>.<sup id="cite_ref-3" class="reference"><a href="#cite_note-3"><span class="cite-bracket">[</span>2<span class="cite-bracket">]</span></a></sup> This means that non-const functions for this object cannot be called from inside such a function, nor can <a href="Field_(computer_science)" title="Field (computer science)">member variables</a> be modified. In C++, a member variable can be declared as <code><a href="Mutable_object" class="mw-redirect" title="Mutable object">mutable</a></code>, indicating that this restriction does not apply to it. In some cases, this can be useful, for example with <a href="Cache_(computing)" title="Cache (computing)">caching</a>, <a href="Reference_counting" title="Reference counting">reference counting</a>, and <a href="Data_synchronization" title="Data synchronization">data synchronization</a>. In these cases, the logical meaning (state) of the object is unchanged, but the object is not physically constant since its bitwise representation may change.
</p>
<div class="mw-heading mw-heading2"><h2 id="Syntax">Syntax</h2></div>
<p>In C, C++, and D, all data types, including those defined by the user, can be declared <code>const</code>, and const-correctness dictates that all variables or objects should be declared as such unless they need to be modified. Such proactive use of <code>const</code> makes values "easier to understand, track, and reason about",<sup id="cite_ref-4" class="reference"><a href="#cite_note-4"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup> and it thus increases the readability and comprehensibility of code and makes working in teams and maintaining code simpler because it communicates information about a value's intended use. This can help the <a href="Compiler" title="Compiler">compiler</a> as well as the developer when reasoning about code. It can also enable an <a href="Optimizing_compiler" title="Optimizing compiler">optimizing compiler</a> to generate more efficient code.<sup id="cite_ref-5" class="reference"><a href="#cite_note-5"><span class="cite-bracket">[</span>4<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading3"><h3 id="Simple_data_types">Simple data types</h3></div>
<p>For simple non-pointer data types, applying the <code>const</code> qualifier is straightforward. It can go on either side of some types for historical reasons (for example, <code>const char foo = 'a';</code> is equivalent to <code>char const foo = 'a';</code>). On some implementations, using <code>const</code> twice (for instance, <code>const char const</code> or <code>char const const</code>) generates a warning but not an error.
</p>
<div class="mw-heading mw-heading3"><h3 id="Pointers_and_references">Pointers and references</h3></div>
<p>For pointer and reference types, the meaning of <code>const</code> is more complicated – either the pointer itself, or the value being pointed to, or both, can be <code>const</code>. Further, the syntax can be confusing. A pointer can be declared as a <code>const</code> pointer to writable value, or a writable pointer to a <code>const</code> value, or <code>const</code> pointer to <code>const</code> value. A <code>const</code> pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the value that it points to (called the <i><a href="Pointee" class="mw-redirect" title="Pointee">pointee</a></i>).<sup id="cite_ref-6" class="reference"><a href="#cite_note-6"><span class="cite-bracket">[</span>5<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-7" class="reference"><a href="#cite_note-7"><span class="cite-bracket">[</span>6<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-8" class="reference"><a href="#cite_note-8"><span class="cite-bracket">[</span>7<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-9" class="reference"><a href="#cite_note-9"><span class="cite-bracket">[</span>8<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-10" class="reference"><a href="#cite_note-10"><span class="cite-bracket">[</span>9<span class="cite-bracket">]</span></a></sup> Reference variables in C++ are an alternate syntax for <code>const</code> pointers. A pointer to a <code>const</code> object, on the other hand, can be reassigned to point to another memory location (which should be an object of the same type or of a convertible type), but it cannot be used to modify the memory that it is pointing to. A <code>const</code> pointer to a <code>const</code> object can also be declared and can neither be used to modify the apointee nor be reassigned to point to another object. The following code illustrates these subtleties:
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="kt">void</span><span class="w"> </span><span class="nf">Foo</span><span class="p">(</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">ptr</span><span class="p">,</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">ptrToConst</span><span class="p">,</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="n">constPtr</span><span class="p">,</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="n">constPtrToConst</span><span class="w"> </span><span class="p">)</span>
<span class="p">{</span>
<span class="w"> </span><span class="o">*</span><span class="n">ptr</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span><span class="w"> </span><span class="c1">// OK: modifies the pointed to data</span>
<span class="w"> </span><span class="n">ptr</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span><span class="w"> </span><span class="c1">// OK: modifies the pointer</span>
<span class="w"> </span><span class="o">*</span><span class="n">ptrToConst</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span><span class="w"> </span><span class="c1">// Error! Cannot modify the pointed to data</span>
<span class="w"> </span><span class="n">ptrToConst</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span><span class="w"> </span><span class="c1">// OK: modifies the pointer</span>
<span class="w"> </span><span class="o">*</span><span class="n">constPtr</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span><span class="w"> </span><span class="c1">// OK: modifies the pointed to data</span>
<span class="w"> </span><span class="n">constPtr</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span><span class="w"> </span><span class="c1">// Error! Cannot modify the pointer</span>
<span class="w"> </span><span class="o">*</span><span class="n">constPtrToConst</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span><span class="w"> </span><span class="c1">// Error! Cannot modify the pointed to data</span>
<span class="w"> </span><span class="n">constPtrToConst</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">NULL</span><span class="p">;</span><span class="w"> </span><span class="c1">// Error! Cannot modify the pointer</span>
<span class="p">}</span>
</pre></div>
<div class="mw-heading mw-heading4"><h4 id="C_convention">C convention</h4></div>
<p>Following usual C convention for declarations, declaration follows use, and the <code>*</code> in a pointer is written on the pointer, indicating <a href="Dereferencing" class="mw-redirect" title="Dereferencing">dereferencing</a>. For example, in the declaration <code>int *ptr</code>, the dereferenced form <code>*ptr</code> is an <code>int</code>, while the reference form <code>ptr</code> is a pointer to an <code>int</code>. Thus <code>const</code> modifies the <i>name</i> to its right. The C++ convention is instead to associate the <code>*</code> with the type, as in <code>int* ptr</code>, and read the <code>const</code> as modifying the <i>type</i> to the left. <code>int const * ptrToConst</code> can thus be read as "<code>*ptrToConst</code> is a <code>int const</code>" (the value is constant), or "<code>ptrToConst</code> is a <code>int const *</code>" (the pointer is a pointer to a constant integer). Thus:
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="n">ptr</span><span class="p">;</span><span class="w"> </span><span class="c1">// *ptr is an int value</span>
<span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">*</span><span class="n">ptrToConst</span><span class="p">;</span><span class="w"> </span><span class="c1">// *ptrToConst is a constant (int: integer value)</span>
<span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="n">constPtr</span><span class="p">;</span><span class="w"> </span><span class="c1">// constPtr is a constant (int *: integer pointer)</span>
<span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="n">constPtrToConst</span><span class="p">;</span><span class="w"> </span><span class="c1">// constPtrToConst is a constant pointer and points</span>
<span class="w"> </span><span class="c1">// to a constant value</span>
</pre></div>
<div class="mw-heading mw-heading4"><h4 id="C++_convention">C++ convention</h4></div>
<p>Following C++ convention of analyzing the type, not the value, a <a href="Rule_of_thumb" title="Rule of thumb">rule of thumb</a> is to read the declaration from right to left. Thus, everything to the left of the star can be identified as the pointed type and everything to the right of the star are the pointer properties. For instance, in our example above, <code>int const *</code> can be read as a writable pointer that refers to a non-writable integer, and <code>int * const</code> can be read as a non-writable pointer that refers to a writable integer.
</p><p>A more generic rule that helps you understand complex declarations and definitions works like this:
</p>
<ol><li>find the identifier whose declaration you want to understand</li>
<li>read as far as possible to the right (i.e., until the end of the declaration or to the next closing parenthesis, whichever comes first)</li>
<li>back up to where you began, and read backwards to the left (i.e., until the beginning of the declaration or to the open-parenthesis matching the closing parenthesis found in the previous step)</li>
<li>when you've reached the beginning of the declaration you're done. If not, continue at step 2, beyond the closing parenthesis that was matched last.</li></ol>
<p>Here is an example:
</p>
<table class="wikitable"><tbody><tr style="vertical-align:top"><th scope="col" style="vertical-align:middle;;"> Part of expression</th><th scope="col" style="vertical-align:middle;;"> <div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">double</span><span class="w"> </span><span class="p">(</span><span class="o">**</span><span class="k">const</span><span class="w"> </span><span class="p">(</span><span class="o">*</span><span class="n">fun</span><span class="p">(</span><span class="kt">int</span><span class="p">))(</span><span class="kt">double</span><span class="p">))[</span><span class="mi">10</span><span class="p">]</span>
</pre></div></th><th scope="col" style="vertical-align:middle;;"> Meaning<br>(reading downwards)</th></tr><tr style="vertical-align:top"><td style="vertical-align:middle;;"> Identifier</td><td style="vertical-align:middle;;"> <div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="w"> </span><span class="n">fun</span>
</pre></div></td><td style="vertical-align:middle;;"> <code>fun</code> is a ...</td></tr><tr style="vertical-align:top"><td style="vertical-align:middle;;"> Read to the right</td><td style="vertical-align:middle;;"> <div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="p">))</span>
</pre></div></td><td style="vertical-align:middle;;"> function expecting an int ...</td></tr><tr style="vertical-align:top"><td style="vertical-align:middle;;"> Find the matching (</td><td style="vertical-align:middle;;"> <div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="w"> </span><span class="p">(</span><span class="o">*</span>
</pre></div></td><td style="vertical-align:middle;;"> returning a pointer to ...</td></tr><tr style="vertical-align:top"><td style="vertical-align:middle;;"> Continue right</td><td style="vertical-align:middle;;"> <div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="w"> </span><span class="p">(</span><span class="kt">double</span><span class="p">))</span>
</pre></div></td><td style="vertical-align:middle;;"> a function expecting a double ...</td></tr><tr style="vertical-align:top"><td style="vertical-align:middle;;"> Find the matching (</td><td style="vertical-align:middle;;"> <div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="w"> </span><span class="p">(</span><span class="o">**</span><span class="k">const</span>
</pre></div></td><td style="vertical-align:middle;;"> returning a constant pointer to<br>a pointer to ...</td></tr><tr style="vertical-align:top"><td style="vertical-align:middle;;"> Continue right</td><td style="vertical-align:middle;;"> <div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="w"> </span><span class="p">[</span><span class="mi">10</span><span class="p">]</span>
</pre></div></td><td style="vertical-align:middle;;"> blocks of 10 ...</td></tr><tr style="vertical-align:top"><td style="vertical-align:middle;;"> Read to the left</td><td style="vertical-align:middle;;"> <div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">double</span>
</pre></div></td><td style="vertical-align:middle;;"> doubles.</td></tr></tbody></table>
<p>When reading to the left, it is important that you read the elements from right to left. So an <code>int const *</code> becomes a <i>pointer to a const int</i> and not a <i>const pointer to an int</i>.
</p><p>In some cases C/C++ allows the <code>const</code> keyword to be placed to the left of the type. Here are some examples:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="k">const</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="n">ptrToConst</span><span class="p">;</span><span class="w"> </span><span class="c1">//identical to: int const *ptrToConst,</span>
<span class="k">const</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="k">const</span><span class="w"> </span><span class="n">constPtrToConst</span><span class="p">;</span><span class="w"> </span><span class="c1">//identical to: int const *const constPtrToConst</span>
</pre></div>
<p>Although C/C++ allows such definitions (which closely match the English language when reading the definitions from left to right), the compiler still reads the definitions according to the abovementioned procedure: from right to left. But putting <code>const</code> <i>before</i> what must be constant quickly introduces mismatches between what you intend to write and what the compiler decides you wrote. Consider pointers to pointers:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">int</span><span class="w"> </span><span class="o">**</span><span class="n">ptr</span><span class="p">;</span><span class="w"> </span><span class="c1">// a pointer to a pointer to ints</span>
<span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">**</span><span class="n">ptr</span><span class="w"> </span><span class="c1">// a pointer to a pointer to constant int value</span>
<span class="w"> </span><span class="c1">// (not a pointer to a constant pointer to ints)</span>
<span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="k">const</span><span class="w"> </span><span class="o">*</span><span class="n">ptr</span><span class="w"> </span><span class="c1">// a pointer to a const pointer to int values</span>
<span class="w"> </span><span class="c1">// (not a constant pointer to a pointer to ints)</span>
<span class="kt">int</span><span class="w"> </span><span class="o">**</span><span class="k">const</span><span class="w"> </span><span class="n">ptr</span><span class="w"> </span><span class="c1">// a constant pointer to pointers to ints</span>
<span class="w"> </span><span class="c1">// (ptr, the identifier, being const makes no sense)</span>
<span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">**</span><span class="k">const</span><span class="w"> </span><span class="n">ptr</span><span class="w"> </span><span class="c1">// a constant pointer to pointers to constant int values</span>
</pre></div>
<p>As a final note regarding pointer definitions: always write the pointer symbol (the *) as much as possible to the right. Attaching the pointer symbol to the type is tricky, as it strongly suggests a pointer type, which isn't the case. Here are some examples:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">int</span><span class="o">*</span><span class="w"> </span><span class="n">a</span><span class="p">;</span><span class="w"> </span><span class="cm">/* write: */</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="n">a</span><span class="p">;</span><span class="w"> </span><span class="c1">// a is a pointer to an int</span>
<span class="kt">int</span><span class="o">*</span><span class="w"> </span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">// CONFUSING </span>
<span class="w"> </span><span class="cm">/* write: */</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">// a is a pointer to an int, </span>
<span class="w"> </span><span class="c1">// but b is a mere int</span>
<span class="kt">int</span><span class="o">*</span><span class="w"> </span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="o">*</span><span class="n">b</span><span class="p">;</span><span class="w"> </span><span class="c1">// UGLY: both a and b are pointers to ints</span>
<span class="w"> </span><span class="cm">/* write: */</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="n">a</span><span class="p">,</span><span class="w"> </span><span class="o">*</span><span class="n">b</span><span class="p">;</span>
</pre></div>
<p>Bjarne Stroustrup's FAQ recommends only declaring one variable per line if using the C++ convention, to avoid this issue.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11"><span class="cite-bracket">[</span>10<span class="cite-bracket">]</span></a></sup>
</p><p>The same considerations apply to defining references and rvalue references:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">int</span><span class="w"> </span><span class="n">var</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">22</span><span class="p">;</span>
<span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">&</span><span class="n">refToConst</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">var</span><span class="p">;</span><span class="w"> </span><span class="c1">// OK</span>
<span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="o">&</span><span class="w"> </span><span class="n">ref2</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">var</span><span class="p">,</span><span class="w"> </span><span class="n">ref3</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">var</span><span class="p">;</span><span class="w"> </span><span class="c1">// CONFUSING:</span>
<span class="w"> </span><span class="c1">// ref2 is a reference, but ref3 isn't:</span>
<span class="w"> </span><span class="c1">// ref3 is a constant int initialized with</span>
<span class="w"> </span><span class="c1">// var's value</span>
<span class="kt">int</span><span class="w"> </span><span class="o">&</span><span class="k">const</span><span class="w"> </span><span class="n">constRef</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">var</span><span class="p">;</span><span class="w"> </span><span class="c1">// ERROR: as references can't change anyway.</span>
<span class="c1">// C++:</span>
<span class="kt">int</span><span class="o">&&</span><span class="w"> </span><span class="n">rref</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kt">int</span><span class="p">(</span><span class="mi">5</span><span class="p">),</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">10</span><span class="p">;</span><span class="w"> </span><span class="c1">// CONFUSING:</span>
<span class="w"> </span><span class="c1">// rref is an rvalue reference, but value is</span>
<span class="w"> </span><span class="c1">// a mere int. </span>
<span class="w"> </span><span class="cm">/* write: */</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="o">&&</span><span class="n">rref</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kt">int</span><span class="p">(</span><span class="mi">5</span><span class="p">),</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">10</span><span class="p">;</span>
</pre></div>
<p>More complicated declarations are encountered when using multidimensional arrays and references (or pointers) to pointers. Although it is sometimes argued that such declarations are confusing and error-prone and that they therefore should be avoided or be replaced by higher-level structures, the procedure described at the top of this section can always be used without introducing ambiguities or confusion.
</p>
<div class="mw-heading mw-heading3"><h3 id="Parameters_and_variables">Parameters and variables</h3></div>
<p><code>const</code> can be declared both on function parameters and on variables (<a href="Static_variable" title="Static variable">static</a> or automatic, including global or local). The interpretation varies between uses. A <code>const</code> static variable (global variable or static local variable) is a constant, and may be used for data like mathematical constants, such as <code>double const PI = 3.14159</code> – realistically longer, or overall compile-time parameters. A <code>const</code> automatic variable (non-static local variable) means that <a href="Single_assignment" class="mw-redirect" title="Single assignment">single assignment</a> is happening, though a different value may be used each time, such as <code>int const x_squared = x * x</code>. A <code>const</code> parameter in pass-by-reference means that the referenced value is not modified – it is part of the <a href="Design_by_contract" title="Design by contract">contract</a> – while a <code>const</code> parameter in pass-by-value (or the pointer itself, in pass-by-reference) does not add anything to the interface (as the value has been copied), but indicates that internally, the function does not modify the local copy of the parameter (it is a single assignment). For this reason, some favor using <code>const</code> in parameters only for pass-by-reference, where it changes the contract, but not for pass-by-value, where it exposes the implementation.
</p>
<div class="mw-heading mw-heading2"><h2 id="C++">C++</h2></div>
<div class="mw-heading mw-heading3"><h3 id="Methods">Methods</h3></div>
<p>In order to take advantage of the <a href="Design_by_contract" title="Design by contract">design by contract</a> approach for user-defined types (structs and classes), which can have methods as well as member data, the programmer may tag instance methods as <code>const</code> if they don't modify the object's data members.
Applying the <code>const</code> qualifier to instance methods thus is an essential feature for const-correctness, and is not available in many other <a href="Object-oriented_programming" title="Object-oriented programming">object-oriented</a> languages such as <a href="Java_(programming_language)" title="Java (programming language)">Java</a> and <a href="C_Sharp_(programming_language)" title="C Sharp (programming language)">C#</a> or in <a href="Microsoft" title="Microsoft">Microsoft</a>'s <a href="C%2B%2B/CLI" title="C++/CLI">C++/CLI</a> or <a href="Managed_Extensions_for_C%2B%2B" title="Managed Extensions for C++">Managed Extensions for C++</a>.
While <code>const</code> methods can be called by <code>const</code> and non-<code>const</code> objects alike, non-<code>const</code> methods can only be invoked by non-<code>const</code> objects.
The <code>const</code> modifier on an instance method applies to the object pointed to by the "<code><a href="This_(computer_science)" class="mw-redirect" title="This (computer science)">this</a></code>" pointer, which is an implicit argument passed to all instance methods.
Thus having <code>const</code> methods is a way to apply const-correctness to the implicit "<code>this</code>" pointer argument just like other arguments.
</p><p>This example illustrates:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="k">class</span><span class="w"> </span><span class="nc">C</span>
<span class="p">{</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="p">;</span>
<span class="k">public</span><span class="o">:</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">Get</span><span class="p">()</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="c1">// Note the "const" tag</span>
<span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">i</span><span class="p">;</span><span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="n">Set</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">j</span><span class="p">)</span><span class="w"> </span><span class="c1">// Note the lack of "const"</span>
<span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">j</span><span class="p">;</span><span class="w"> </span><span class="p">}</span>
<span class="p">};</span>
<span class="kt">void</span><span class="w"> </span><span class="nf">Foo</span><span class="p">(</span><span class="n">C</span><span class="o">&</span><span class="w"> </span><span class="n">nonConstC</span><span class="p">,</span><span class="w"> </span><span class="n">C</span><span class="w"> </span><span class="k">const</span><span class="o">&</span><span class="w"> </span><span class="n">constC</span><span class="p">)</span>
<span class="p">{</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">y</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">nonConstC</span><span class="p">.</span><span class="n">Get</span><span class="p">();</span><span class="w"> </span><span class="c1">// Ok</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">constC</span><span class="p">.</span><span class="n">Get</span><span class="p">();</span><span class="w"> </span><span class="c1">// Ok: Get() is const</span>
<span class="w"> </span><span class="n">nonConstC</span><span class="p">.</span><span class="n">Set</span><span class="p">(</span><span class="mi">10</span><span class="p">);</span><span class="w"> </span><span class="c1">// Ok: nonConstC is modifiable</span>
<span class="w"> </span><span class="n">constC</span><span class="p">.</span><span class="n">Set</span><span class="p">(</span><span class="mi">10</span><span class="p">);</span><span class="w"> </span><span class="c1">// Error! Set() is a non-const method and constC is a const-qualified object</span>
<span class="p">}</span>
</pre></div>
<p>In the above code, the implicit "<code>this</code>" pointer to <code>Set()</code> has the type "<code>C *const</code>"; whereas the "<code>this</code>" pointer to <code>Get()</code> has type "<code>C const *const</code>", indicating that the method cannot modify its object through the "<code>this</code>" pointer.
</p><p>Often the programmer will supply both a <code>const</code> and a non-<code>const</code> method with the same name (but possibly quite different uses) in a class to accommodate both types of callers. Consider:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="k">class</span><span class="w"> </span><span class="nc">MyArray</span>
<span class="p">{</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">data</span><span class="p">[</span><span class="mi">100</span><span class="p">];</span>
<span class="k">public</span><span class="o">:</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="o">&</span><span class="w"> </span><span class="n">Get</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">data</span><span class="p">[</span><span class="n">i</span><span class="p">];</span><span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">&</span><span class="w"> </span><span class="n">Get</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="p">)</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">data</span><span class="p">[</span><span class="n">i</span><span class="p">];</span><span class="w"> </span><span class="p">}</span>
<span class="p">};</span>
<span class="kt">void</span><span class="w"> </span><span class="nf">Foo</span><span class="p">(</span><span class="w"> </span><span class="n">MyArray</span><span class="w"> </span><span class="o">&</span><span class="w"> </span><span class="n">array</span><span class="p">,</span><span class="w"> </span><span class="n">MyArray</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">&</span><span class="w"> </span><span class="n">constArray</span><span class="w"> </span><span class="p">)</span>
<span class="p">{</span>
<span class="w"> </span><span class="c1">// Get a reference to an array element</span>
<span class="w"> </span><span class="c1">// and modify its referenced value.</span>
<span class="w"> </span><span class="n">array</span><span class="p">.</span><span class="n">Get</span><span class="p">(</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">)</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">42</span><span class="p">;</span><span class="w"> </span><span class="c1">// OK! (Calls: int & MyArray::Get(int))</span>
<span class="w"> </span><span class="n">constArray</span><span class="p">.</span><span class="n">Get</span><span class="p">(</span><span class="w"> </span><span class="mi">5</span><span class="w"> </span><span class="p">)</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">42</span><span class="p">;</span><span class="w"> </span><span class="c1">// Error! (Calls: int const & MyArray::Get(int) const)</span>
<span class="p">}</span>
</pre></div>
<p>The <code>const</code>-ness of the calling object determines which version of <code>MyArray::Get()</code> will be invoked and thus whether or not the caller is given a reference with which he can manipulate or only observe the private data in the object.
The two methods technically have different signatures because their "<code>this</code>" pointers have different types, allowing the compiler to choose the right one. (Returning a <code>const</code> reference to an <code>int</code>, instead of merely returning the <code>int</code> by value, may be overkill in the second method, but the same technique can be used for arbitrary types, as in the <a href="Standard_Template_Library" title="Standard Template Library">Standard Template Library</a>.)
</p>
<div class="mw-heading mw-heading2"><h2 id="Loopholes_to_const-correctness">Loopholes to const-correctness</h2></div>
<p>There are several loopholes to pure const-correctness in C and C++. They exist primarily for compatibility with existing code.
</p><p>The first, which applies only to C++, is the use of <code>const_cast</code>, which allows the programmer to strip the <code>const</code> qualifier, making any object modifiable.
The necessity of stripping the qualifier arises when using existing code and libraries that cannot be modified but which are not const-correct. For instance, consider this code:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="c1">// Prototype for a function which we cannot change but which</span>
<span class="c1">// we know does not modify the pointee passed in.</span>
<span class="kt">void</span><span class="w"> </span><span class="nf">LibraryFunc</span><span class="p">(</span><span class="kt">int</span><span class="o">*</span><span class="w"> </span><span class="n">ptr</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">size</span><span class="p">);</span>
<span class="kt">void</span><span class="w"> </span><span class="nf">CallLibraryFunc</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">ptr</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">size</span><span class="p">)</span>
<span class="p">{</span>
<span class="w"> </span><span class="n">LibraryFunc</span><span class="p">(</span><span class="n">ptr</span><span class="p">,</span><span class="w"> </span><span class="n">size</span><span class="p">);</span><span class="w"> </span><span class="c1">// Error! Drops const qualifier</span>
<span class="w"> </span><span class="kt">int</span><span class="o">*</span><span class="w"> </span><span class="n">nonConstPtr</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">const_cast</span><span class="o"><</span><span class="kt">int</span><span class="o">*></span><span class="p">(</span><span class="n">ptr</span><span class="p">);</span><span class="w"> </span><span class="c1">// Strip qualifier</span>
<span class="w"> </span><span class="n">LibraryFunc</span><span class="p">(</span><span class="n">nonConstPtr</span><span class="p">,</span><span class="w"> </span><span class="n">size</span><span class="p">);</span><span class="w"> </span><span class="c1">// OK</span>
<span class="p">}</span>
</pre></div>
<p>However, any attempt to modify an object that is itself declared <code>const</code> by means of a <a href="Const_cast" class="mw-redirect" title="Const cast">const cast</a> results in undefined behavior according to the ISO C++ Standard.
In the example above, if <code>ptr</code> references a global, local, or member variable declared as <code>const</code>, or an object allocated on the heap via <code>new int const</code>, the code is only correct if <code>LibraryFunc</code> really does not modify the value pointed to by <code>ptr</code>.
</p><p>The C language has a need of a loophole because a certain situation exists. Variables with static storage duration are allowed to be defined with an initial value. However, the initializer can use only constants like string constants and other literals, and is not allowed to use non-constant elements like variable names, whether the initializer elements are declared <code>const</code> or not, or whether the static duration variable is being declared <code>const</code> or not. There is a non-portable way to initialize a <code>const</code> variable that has static storage duration. By carefully constructing a typecast on the left hand side of a later assignment, a <code>const</code> variable can be written to, effectively stripping away the <code>const</code> attribute and 'initializing' it with non-constant elements like other <code>const</code> variables and such. Writing into a <code>const</code> variable this way may work as intended, but it causes undefined behavior and seriously contradicts const-correctness:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">size_t</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="n">bufferSize</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">8</span><span class="o">*</span><span class="mi">1024</span><span class="p">;</span>
<span class="kt">size_t</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="n">userTextBufferSize</span><span class="p">;</span><span class="w"> </span><span class="c1">// initial value depends on const bufferSize, can't be initialized here</span>
<span class="p">...</span>
<span class="kt">int</span><span class="w"> </span><span class="n">setupUserTextBox</span><span class="p">(</span><span class="n">textBox_t</span><span class="w"> </span><span class="o">*</span><span class="n">defaultTextBoxType</span><span class="p">,</span><span class="w"> </span><span class="n">rect_t</span><span class="w"> </span><span class="o">*</span><span class="n">defaultTextBoxLocation</span><span class="p">)</span>
<span class="p">{</span>
<span class="w"> </span><span class="o">*</span><span class="p">(</span><span class="kt">size_t</span><span class="o">*</span><span class="p">)</span><span class="o">&</span><span class="n">userTextBufferSize</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">bufferSize</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="k">sizeof</span><span class="p">(</span><span class="k">struct</span><span class="w"> </span><span class="nc">textBoxControls</span><span class="p">);</span><span class="w"> </span><span class="c1">// warning: might work, but not guaranteed by C</span>
<span class="w"> </span><span class="p">...</span>
<span class="p">}</span>
</pre></div>
<p>Another loophole<sup id="cite_ref-12" class="reference"><a href="#cite_note-12"><span class="cite-bracket">[</span>11<span class="cite-bracket">]</span></a></sup> applies both to C and C++. Specifically, the languages dictate that member pointers and references are "shallow" with respect to the <code>const</code>-ness of their owners – that is, a containing object that is <code>const</code> has all <code>const</code> members except that member pointees (and referees) are still mutable. To illustrate, consider this C++ code:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="k">struct</span><span class="w"> </span><span class="nc">S</span>
<span class="p">{</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">val</span><span class="p">;</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="o">*</span><span class="n">ptr</span><span class="p">;</span>
<span class="p">};</span>
<span class="kt">void</span><span class="w"> </span><span class="nf">Foo</span><span class="p">(</span><span class="n">S</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">&</span><span class="w"> </span><span class="n">s</span><span class="p">)</span>
<span class="p">{</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">42</span><span class="p">;</span>
<span class="w"> </span><span class="n">s</span><span class="p">.</span><span class="n">val</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">i</span><span class="p">;</span><span class="w"> </span><span class="c1">// Error: s is const, so val is a const int</span>
<span class="w"> </span><span class="n">s</span><span class="p">.</span><span class="n">ptr</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="o">&</span><span class="n">i</span><span class="p">;</span><span class="w"> </span><span class="c1">// Error: s is const, so ptr is a const pointer to int</span>
<span class="w"> </span><span class="o">*</span><span class="n">s</span><span class="p">.</span><span class="n">ptr</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">i</span><span class="p">;</span><span class="w"> </span><span class="c1">// OK: the data pointed to by ptr is always mutable,</span>
<span class="w"> </span><span class="c1">// even though this is sometimes not desirable</span>
<span class="p">}</span>
</pre></div>
<p>Although the object <code>s</code> passed to <code>Foo()</code> is constant, which makes all of its members constant, the pointee accessible through <code>s.ptr</code> is still modifiable, though this may not be desirable from the standpoint of <code>const</code>-correctness because <code>s</code> might solely own the pointee.
For this reason, Meyers argues that the default for member pointers and references should be "deep" <code>const</code>-ness, which could be overridden by a <code>mutable</code> qualifier when the pointee is not owned by the container, but this strategy would create compatibility issues with existing code.
Thus, for historical reasons, this loophole remains open in C and C++.
</p><p>The latter loophole can be closed by using a class to hide the pointer behind a <code>const</code>-correct interface, but such classes either do not support the usual copy semantics from a <code>const</code> object (implying that the containing class cannot be copied by the usual semantics either) or allow other loopholes by permitting the stripping of <code>const</code>-ness through inadvertent or intentional copying.
</p><p>Finally, several functions in the <a href="C_standard_library" title="C standard library">C standard library</a> violate const-correctness before <a href="C23_(C_standard_revision)" title="C23 (C standard revision)">C23</a>, as they accept a <code>const</code> pointer to a character string and return a non-<code>const</code> pointer to a part of the same string. <code><a href="Strstr" class="mw-redirect" title="Strstr">strstr</a></code> and <code><a href="Strchr" class="mw-redirect" title="Strchr">strchr</a></code> are among these functions.
Some implementations of the C++ standard library, such as Microsoft's<sup id="cite_ref-13" class="reference"><a href="#cite_note-13"><span class="cite-bracket">[</span>12<span class="cite-bracket">]</span></a></sup> try to close this loophole by providing two <a href="Function_overloading" title="Function overloading">overloaded</a> versions of some functions: a "<code>const</code>" version and a "non-<code>const</code>" version.
</p>
<div class="mw-heading mw-heading2"><h2 id="Problems">Problems</h2></div>
<style data-mw-deduplicate="TemplateStyles:r1251242444">
/* start https://en.wikipedia.org/ */
.mw-parser-output .ambox{border:1px solid #a2a9b1;border-left:10px solid #36c;background-color:#fbfbfb;box-sizing:border-box}.mw-parser-output .ambox+link+.ambox,.mw-parser-output .ambox+link+style+.ambox,.mw-parser-output .ambox+link+link+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+style+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+link+.ambox{margin-top:-1px}html body.mediawiki .mw-parser-output .ambox.mbox-small-left{margin:4px 1em 4px 0;overflow:hidden;width:238px;border-collapse:collapse;font-size:88%;line-height:1.25em}.mw-parser-output .ambox-speedy{border-left:10px solid #b32424;background-color:#fee7e6}.mw-parser-output .ambox-delete{border-left:10px solid #b32424}.mw-parser-output .ambox-content{border-left:10px solid #f28500}.mw-parser-output .ambox-style{border-left:10px solid #fc3}.mw-parser-output .ambox-move{border-left:10px solid #9932cc}.mw-parser-output .ambox-protection{border-left:10px solid #a2a9b1}.mw-parser-output .ambox .mbox-text{border:none;padding:0.25em 0.5em;width:100%}.mw-parser-output .ambox .mbox-image{border:none;padding:2px 0 2px 0.5em;text-align:center}.mw-parser-output .ambox .mbox-imageright{border:none;padding:2px 0.5em 2px 0;text-align:center}.mw-parser-output .ambox .mbox-empty-cell{border:none;padding:0;width:1px}.mw-parser-output .ambox .mbox-image-div{width:52px}@media(min-width:720px){.mw-parser-output .ambox{margin:0 10%}}@media print{body.ns-0 .mw-parser-output .ambox{display:none!important}}
/* end https://en.wikipedia.org/ */
</style>
<p>The use of the type system to express constancy leads to various complexities and problems, and has accordingly been criticized and not adopted outside the narrow C family of C, C++, and D. Java and C#, which are heavily influenced by C and C++, both explicitly rejected <code>const</code>-style type qualifiers, instead expressing constancy by keywords that apply to the identifier (<code>final</code> in Java, <code>const</code> and <code>readonly</code> in C#). Even within C and C++, the use of <code>const</code> varies significantly, with some projects and organizations using it consistently, and others avoiding it.
</p>
<div class="mw-heading mw-heading3"><h3 id="strchr_problem"><code>strchr</code> problem</h3></div>
<p>The <code>const</code> type qualifier causes difficulties when the logic of a function is agnostic to whether its input is constant or not, but returns a value which should be of the same qualified type as an input. In other words, for these functions, if the input is constant (const-qualified), the return value should be as well, but if the input is variable (not <code>const</code>-qualified), the return value should be as well. Because the <a href="Type_signature" title="Type signature">type signature</a> of these functions differs, it requires two functions (or potentially more, in case of multiple inputs) with the same logic – a form of <a href="Generic_programming" title="Generic programming">generic programming</a>.
</p><p>This problem arises even for simple functions in the C standard library, notably <code>strchr</code>; this observation is credited by Ritchie to Tom Plum in the mid 1980s.<sup id="cite_ref-14" class="reference"><a href="#cite_note-14"><span class="cite-bracket">[</span>13<span class="cite-bracket">]</span></a></sup> The <code>strchr</code> function locates a character in a string; formally, it returns a pointer to the first occurrence of the character <code>c</code> in the string <code>s</code>, and in classic C (K&R C) its prototype is:
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="nf">strchr</span><span class="p">(</span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">s</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">c</span><span class="p">);</span>
</pre></div>
<p>The <code>strchr</code> function does not modify the input string, but the return value is often used by the caller to modify the string, such as:
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">p</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">strchr</span><span class="p">(</span><span class="n">q</span><span class="p">,</span><span class="w"> </span><span class="sc">'/'</span><span class="p">))</span>
<span class="w"> </span><span class="o">*</span><span class="n">p</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="sc">' '</span><span class="p">;</span>
</pre></div>
<p>Thus on the one hand the input string <i>can</i> be <code>const</code> (since it is not modified by the function), and if the input string is <code>const</code> the return value should be as well – most simply because it might return exactly the input pointer, if the first character is a match – but on the other hand the return value should not be <code>const</code> if the original string was not <code>const</code>, since the caller may wish to use the pointer to modify the original string.
</p><p>In C++ this is done via <a href="Function_overloading" title="Function overloading">function overloading</a>, typically implemented via a <a href="Template_(C%2B%2B)" title="Template (C++)">template</a>, resulting in two functions, so that the return value has the same <code>const</code>-qualified type as the input:<sup id="cite_ref-15" class="reference"><a href="#cite_note-15"><span class="cite-bracket">[</span>b<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">char</span><span class="o">*</span><span class="w"> </span><span class="nf">strchr</span><span class="p">(</span><span class="kt">char</span><span class="o">*</span><span class="w"> </span><span class="n">s</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">c</span><span class="p">);</span>
<span class="kt">char</span><span class="w"> </span><span class="k">const</span><span class="o">*</span><span class="w"> </span><span class="n">strchr</span><span class="p">(</span><span class="kt">char</span><span class="w"> </span><span class="k">const</span><span class="o">*</span><span class="w"> </span><span class="n">s</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">c</span><span class="p">);</span>
</pre></div>
<p>These can in turn be defined by a template:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="k">template</span><span class="w"> </span><span class="o"><</span><span class="n">T</span><span class="o">></span>
<span class="n">T</span><span class="o">*</span><span class="w"> </span><span class="n">strchr</span><span class="p">(</span><span class="n">T</span><span class="o">*</span><span class="w"> </span><span class="n">s</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">c</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="p">...</span><span class="w"> </span><span class="p">}</span>
</pre></div>
<p>In D this is handled via the <code>inout</code> keyword, which acts as a wildcard for const, immutable, or unqualified (variable), yielding:<sup id="cite_ref-d8_8_16-0" class="reference"><a href="#cite_note-d8_8-16"><span class="cite-bracket">[</span>14<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-17" class="reference"><a href="#cite_note-17"><span class="cite-bracket">[</span>c<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-highlight mw-highlight-lang-d mw-content-ltr" dir="ltr"><pre><span class="k">inout</span><span class="p">(</span><span class="kt">char</span><span class="p">)*</span><span class="w"> </span><span class="n">strchr</span><span class="p">(</span><span class="k">inout</span><span class="p">(</span><span class="kt">char</span><span class="p">)*</span><span class="w"> </span><span class="n">s</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">c</span><span class="p">);</span>
</pre></div>
<p>However, in C neither of these is possible<sup id="cite_ref-18" class="reference"><a href="#cite_note-18"><span class="cite-bracket">[</span>d<span class="cite-bracket">]</span></a></sup> since C does not have function overloading, and instead, this is handled by having a single function where the input is constant but the output is writable:
</p>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="nf">strchr</span><span class="p">(</span><span class="kt">char</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">*</span><span class="n">s</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">c</span><span class="p">);</span>
</pre></div>
<p>This allows idiomatic C code but does strip the const qualifier if the input actually was const-qualified, violating type safety. This solution was proposed by Ritchie and subsequently adopted. This difference is one of the failures of <a href="Compatibility_of_C_and_C%2B%2B" title="Compatibility of C and C++">compatibility of C and C++</a>.
</p><p>Since <a href="C23_(C_standard_revision)" title="C23 (C standard revision)">C23</a>, this problem is solved with the use of the <code>_Generic</code> facility of the language: the identifiers of <code>strchr</code> and the other functions affected by the issue have been turned into macros that expand a call to an appropriate function which will return a <code>const</code> pointer if one was passed to them and an unqualified pointer if an unqualified pointer was passed to them.<sup id="cite_ref-N3020_19-0" class="reference"><a href="#cite_note-N3020-19"><span class="cite-bracket">[</span>15<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="D">D</h2></div>
<p>In version 2 of the <a href="D_(programming_language)" title="D (programming language)">D programming language</a>, two keywords relating to const exist.<sup id="cite_ref-20" class="reference"><a href="#cite_note-20"><span class="cite-bracket">[</span>16<span class="cite-bracket">]</span></a></sup> The <code>immutable</code> keyword denotes data that cannot be modified through any reference.
The <code>const</code> keyword denotes a non-mutable view of mutable data.
Unlike C++ <code>const</code>, D <code>const</code> and <code>immutable</code> are "deep" or <a href="Transitive_relation" title="Transitive relation">transitive</a>, and anything reachable through a <code>const</code> or <code>immutable</code> object is <code>const</code> or <code>immutable</code> respectively.
</p><p><b>Example of const vs. immutable in D</b>
</p>
<div class="mw-highlight mw-highlight-lang-d mw-content-ltr" dir="ltr"><pre><span class="kt">int</span><span class="p">[]</span><span class="w"> </span><span class="n">foo</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="kt">int</span><span class="p">[</span><span class="mi">5</span><span class="p">];</span><span class="w"> </span><span class="c1">// foo is mutable.</span>
<span class="k">const</span><span class="w"> </span><span class="kt">int</span><span class="p">[]</span><span class="w"> </span><span class="n">bar</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="n">foo</span><span class="p">;</span><span class="w"> </span><span class="c1">// bar is a const view of mutable data.</span>
<span class="k">immutable</span><span class="w"> </span><span class="kt">int</span><span class="p">[]</span><span class="w"> </span><span class="n">baz</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="n">foo</span><span class="p">;</span><span class="w"> </span><span class="c1">// Error: all views of immutable data must be immutable.</span>
<span class="k">immutable</span><span class="w"> </span><span class="kt">int</span><span class="p">[]</span><span class="w"> </span><span class="n">nums</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="k">immutable</span><span class="p">(</span><span class="kt">int</span><span class="p">)[</span><span class="mi">5</span><span class="p">];</span><span class="w"> </span><span class="c1">// No mutable reference to nums may be created.</span>
<span class="k">const</span><span class="w"> </span><span class="kt">int</span><span class="p">[]</span><span class="w"> </span><span class="n">constNums</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="n">nums</span><span class="p">;</span><span class="w"> </span><span class="c1">// Works. immutable is implicitly convertible to const.</span>
<span class="kt">int</span><span class="p">[]</span><span class="w"> </span><span class="n">mutableNums</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="n">nums</span><span class="p">;</span><span class="w"> </span><span class="c1">// Error: Cannot create a mutable view of immutable data.</span>
</pre></div>
<p><b>Example of transitive or deep const in D</b>
</p>
<div class="mw-highlight mw-highlight-lang-d mw-content-ltr" dir="ltr"><pre><span class="k">class</span><span class="w"> </span><span class="n">Foo</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="n">Foo</span><span class="w"> </span><span class="n">next</span><span class="p">;</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">num</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">immutable</span><span class="w"> </span><span class="n">Foo</span><span class="w"> </span><span class="n">foo</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="k">immutable</span><span class="p">(</span><span class="n">Foo</span><span class="p">);</span>
<span class="n">foo</span><span class="p">.</span><span class="n">next</span><span class="p">.</span><span class="n">num</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="mi">5</span><span class="p">;</span><span class="w"> </span><span class="c1">// Won't compile. foo.next is of type immutable(Foo).</span>
<span class="w"> </span><span class="c1">// foo.next.num is of type immutable(int).</span>
</pre></div>
<div class="mw-heading mw-heading2"><h2 id="History">History</h2></div>
<p><code>const</code> was introduced by <a href="Bjarne_Stroustrup" title="Bjarne Stroustrup">Bjarne Stroustrup</a> in <a href="C_with_Classes" class="mw-redirect" title="C with Classes">C with Classes</a>, the predecessor to <a href="C%2B%2B" title="C++">C++</a>, in 1981, and was originally called <code>readonly</code>.<sup id="cite_ref-21" class="reference"><a href="#cite_note-21"><span class="cite-bracket">[</span>17<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-siblings_22-0" class="reference"><a href="#cite_note-siblings-22"><span class="cite-bracket">[</span>18<span class="cite-bracket">]</span></a></sup> As to motivation, Stroustrup writes:<sup id="cite_ref-siblings_22-1" class="reference"><a href="#cite_note-siblings-22"><span class="cite-bracket">[</span>18<span class="cite-bracket">]</span></a></sup>
</p>
<dl><dd>"It served two functions: as a way of defining a symbolic constant that obeys scope and type rules (that is, without using a macro) and as a way of deeming an object in memory immutable."</dd></dl>
<p>The first use, as a scoped and typed alternative to macros, was analogously fulfilled for function-like macros via the <code>inline</code> keyword. Constant pointers, and the <code>* const</code> notation, were suggested by Dennis Ritchie and so adopted.<sup id="cite_ref-siblings_22-2" class="reference"><a href="#cite_note-siblings-22"><span class="cite-bracket">[</span>18<span class="cite-bracket">]</span></a></sup>
</p><p><code>const</code> was then adopted in C as part of standardization, and appears in <a href="ANSI_C" title="ANSI C">C89</a> (and subsequent versions) along with the other type qualifier, <code>volatile</code>.<sup id="cite_ref-23" class="reference"><a href="#cite_note-23"><span class="cite-bracket">[</span>19<span class="cite-bracket">]</span></a></sup> A further qualifier, <code>noalias</code>, was suggested at the December 1987 meeting of the X3J11 committee, but was rejected; its goal was ultimately fulfilled by the <code><a href="Restrict" title="Restrict">restrict</a></code> keyword in <a href="C99" title="C99">C99</a>. Ritchie was not very supportive of these additions, arguing that they did not "carry their weight", but ultimately did not argue for their removal from the standard.<sup id="cite_ref-24" class="reference"><a href="#cite_note-24"><span class="cite-bracket">[</span>20<span class="cite-bracket">]</span></a></sup>
</p><p>D subsequently inherited <code>const</code> from C++, where it is known as a <i>type constructor</i> (not <a href="Type_qualifier" title="Type qualifier">type qualifier</a>) and added two further type constructors, <code>immutable</code> and <code>inout</code>, to handle related use cases.<sup id="cite_ref-25" class="reference"><a href="#cite_note-25"><span class="cite-bracket">[</span>e<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="Other_languages">Other languages</h2></div>
<p>Other languages do not follow C/C++ in having constancy part of the type, though they often have superficially similar constructs and may use the <code>const</code> keyword. Typically this is only used for constants (constant objects).
</p><p><a href="C_Sharp_(programming_language)" title="C Sharp (programming language)">C#</a> has a <code>const</code> keyword, but with radically different and simpler semantics: it means a compile-time constant, and is not part of the type.
</p><p><a href="Nim_(programming_language)" title="Nim (programming language)">Nim</a> has a <code>const</code> keyword similar to that of C#: it also declares a compile-time constant rather than forming part of the type. However, in Nim, a constant can be declared from any expression that can be evaluated at compile time.<sup id="cite_ref-26" class="reference"><a href="#cite_note-26"><span class="cite-bracket">[</span>21<span class="cite-bracket">]</span></a></sup> In C#, only C# built-in types can be declared as <code>const</code>; user-defined types, including classes, structs, and arrays, cannot be <code>const</code>.<sup id="cite_ref-27" class="reference"><a href="#cite_note-27"><span class="cite-bracket">[</span>22<span class="cite-bracket">]</span></a></sup>
</p><p><a href="Java_(programming_language)" title="Java (programming language)">Java</a> does not have <code>const</code> – it instead has <code>final</code>, which can be applied to local "variable" declarations and applies to the <i>identifier</i>, not the type. It has a different object-oriented use for object members, which is the origin of the name.
</p><p>The Java language specification regards <code>const</code> as a reserved keyword – i.e., one that cannot be used as variable identifier – but assigns no semantics to it: it is a <i>reserved word</i> (it cannot be used in identifiers) but not a <i>keyword</i> (it has no special meaning). The keyword was included as a means for Java compilers to detect and warn about the incorrect usage of C++ keywords.<sup id="cite_ref-28" class="reference"><a href="#cite_note-28"><span class="cite-bracket">[</span>23<span class="cite-bracket">]</span></a></sup> An enhancement request ticket for implementing <code>const</code> correctness exists in the <a href="Java_Community_Process" title="Java Community Process">Java Community Process</a>, but was closed in 2005 on the basis that it was impossible to implement in a backwards-compatible fashion.<sup id="cite_ref-29" class="reference"><a href="#cite_note-29"><span class="cite-bracket">[</span>24<span class="cite-bracket">]</span></a></sup>
</p><p>The contemporary <a href="Ada_83" class="mw-redirect" title="Ada 83">Ada 83</a> independently had the notion of a constant object and a <code>constant</code> keyword,<sup id="cite_ref-30" class="reference"><a href="#cite_note-30"><span class="cite-bracket">[</span>25<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-31" class="reference"><a href="#cite_note-31"><span class="cite-bracket">[</span>f<span class="cite-bracket">]</span></a></sup> with <a href="Input_parameter" class="mw-redirect" title="Input parameter">input parameters</a> and loop parameters being implicitly constant. Here the <code>constant</code> is a property of the object, not of the type.
</p><p><a href="JavaScript" title="JavaScript">JavaScript</a> has a <code>const</code> declaration that defines a <a href="Block_scope" class="mw-redirect" title="Block scope">block-scoped</a> variable that cannot be reassigned nor redeclared. It defines a read-only reference to a variable that cannot be redefined, but in some situations the value of the variable itself may potentially change, such as if the variable refers to an object and a property of it is altered.<sup id="cite_ref-32" class="reference"><a href="#cite_note-32"><span class="cite-bracket">[</span>26<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="See_also">See also</h2></div>
<ul><li><a href="Single_assignment" class="mw-redirect" title="Single assignment">Single assignment</a></li>
<li><a href="Restrict" title="Restrict">restrict</a></li>
<li><a href="Pointer_aliasing" class="mw-redirect" title="Pointer aliasing">Pointer aliasing</a></li></ul>
<div class="mw-heading mw-heading2"><h2 id="Notes">Notes</h2></div>
<style data-mw-deduplicate="TemplateStyles:r1239543626">
/* start https://en.wikipedia.org/ */
.mw-parser-output .reflist{margin-bottom:0.5em;list-style-type:decimal}@media screen{.mw-parser-output .reflist{font-size:90%}}.mw-parser-output .reflist .references{font-size:100%;margin-bottom:0;list-style-type:inherit}.mw-parser-output .reflist-columns-2{column-width:30em}.mw-parser-output .reflist-columns-3{column-width:25em}.mw-parser-output .reflist-columns{margin-top:0.3em}.mw-parser-output .reflist-columns ol{margin-top:0}.mw-parser-output .reflist-columns li{page-break-inside:avoid;break-inside:avoid-column}.mw-parser-output .reflist-upper-alpha{list-style-type:upper-alpha}.mw-parser-output .reflist-upper-roman{list-style-type:upper-roman}.mw-parser-output .reflist-lower-alpha{list-style-type:lower-alpha}.mw-parser-output .reflist-lower-greek{list-style-type:lower-greek}.mw-parser-output .reflist-lower-roman{list-style-type:lower-roman}
/* end https://en.wikipedia.org/ */
</style><div class="reflist reflist-lower-alpha">
<div class="mw-references-wrap"><ol class="references">
<li id="cite_note-2"><span class="mw-cite-backlink"><b><a href="#cite_ref-2">^</a></b></span> <span class="reference-text">Formally when the <code>const</code> is part of the outermost derived type in a declaration; pointers complicate discussion.</span>
</li>
<li id="cite_note-15"><span class="mw-cite-backlink"><b><a href="#cite_ref-15">^</a></b></span> <span class="reference-text">Note that pointer declaration syntax conventions differ between C and C++: in C <code>char *s</code> is standard, while in C++ <code>char* s</code> is standard.</span>
</li>
<li id="cite_note-17"><span class="mw-cite-backlink"><b><a href="#cite_ref-17">^</a></b></span> <span class="reference-text">Idiomatic D code would use an array here instead of a pointer.<sup id="cite_ref-d8_8_16-1" class="reference"><a href="#cite_note-d8_8-16"><span class="cite-bracket">[</span>14<span class="cite-bracket">]</span></a></sup></span>
</li>
<li id="cite_note-18"><span class="mw-cite-backlink"><b><a href="#cite_ref-18">^</a></b></span> <span class="reference-text">In C11 and later <code>_Generic</code> could have been used to implement a const-correct <code>strchr</code>.
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="kt">char</span><span class="o">*</span><span class="w"> </span><span class="nf">strchr_m</span><span class="p">(</span><span class="kt">char</span><span class="w"> </span><span class="o">*</span><span class="n">s</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">c</span><span class="p">);</span>
<span class="kt">char</span><span class="w"> </span><span class="k">const</span><span class="o">*</span><span class="w"> </span><span class="n">strchr_c</span><span class="p">(</span><span class="kt">char</span><span class="w"> </span><span class="k">const</span><span class="w"> </span><span class="o">*</span><span class="n">s</span><span class="p">,</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">c</span><span class="p">);</span>
<span class="cp">#define strchr(X,Y) _Generic((X), \</span>
<span class="cp"> char*: strchr_m, \</span>
<span class="cp"> const char*: strchr_c \</span>
<span class="cp"> )(X,Y)</span>
</pre></div></span>
</li>
<li id="cite_note-25"><span class="mw-cite-backlink"><b><a href="#cite_ref-25">^</a></b></span> <span class="reference-text">D also introduced the <code>shared</code> type constructor, but this is related to use cases of <code>volatile</code>, not <code>const</code>.</span>
</li>
<li id="cite_note-31"><span class="mw-cite-backlink"><b><a href="#cite_ref-31">^</a></b></span> <span class="reference-text">The Ada standard calls this a "<a href="Reserved_word" title="Reserved word">reserved word</a>"; see that article for usage.</span>
</li>
</ol></div></div>
<div class="mw-heading mw-heading2"><h2 id="References">References</h2></div>
<div class="reflist">
<div class="mw-references-wrap mw-references-columns"><ol class="references">
<li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text"><style data-mw-deduplicate="TemplateStyles:r1238218222">
/* start https://en.wikipedia.org/ */
.mw-parser-output cite.citation{font-style:inherit;word-wrap:break-word}.mw-parser-output .citation q{quotes:"\"""\"""'""'"}.mw-parser-output .citation:target{background-color:rgba(0,127,255,0.133)}.mw-parser-output .id-lock-free.id-lock-free a{background:url("./mw/Lock-green.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-limited.id-lock-limited a,.mw-parser-output .id-lock-registration.id-lock-registration a{background:url("./mw/Lock-gray-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-subscription.id-lock-subscription a{background:url("./mw/Lock-red-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .cs1-ws-icon a{background:url("./mw/Wikisource-logo.svg")right 0.1em center/12px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-free a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-limited a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-registration a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-subscription a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .cs1-ws-icon a{background-size:contain;padding:0 1em 0 0}.mw-parser-output .cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;color:var(--color-error,#d33)}.mw-parser-output .cs1-visible-error{color:var(--color-error,#d33)}.mw-parser-output .cs1-maint{display:none;color:#085;margin-left:0.3em}.mw-parser-output .cs1-kern-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}@media screen{.mw-parser-output .cs1-format{font-size:95%}html.skin-theme-clientpref-night .mw-parser-output .cs1-maint{color:#18911f}}@media screen and (prefers-color-scheme:dark){html.skin-theme-clientpref-os .mw-parser-output .cs1-maint{color:#18911f}}
/* end https://en.wikipedia.org/ */
</style><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://doc.rust-lang.org/reference/items/constant-items.html">"Constant items – The Rust Reference"</a>. <i>doc.rust-lang.org</i><span class="reference-accessdate">. Retrieved <span class="nowrap">2022-06-22</span></span>.</cite></span>
</li>
<li id="cite_note-3"><span class="mw-cite-backlink"><b><a href="#cite_ref-3">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://eel.is/c++draft/class.this#:this,type_of">"The <code>this</code> pointer"</a>. <i>Draft C++ Standard</i><span class="reference-accessdate">. Retrieved <span class="nowrap">2020-03-30</span></span>. <q>The type of <code>this</code> in a member function whose type has a <i>cv-qualifier-seq cv</i> and whose class is <code>X</code> is "pointer to <i>cv</i> <code>X</code>".</q></cite></span>
</li>
<li id="cite_note-4"><span class="mw-cite-backlink"><b><a href="#cite_ref-4">^</a></b></span> <span class="reference-text"><a href="Herb_Sutter" title="Herb Sutter">Herb Sutter</a> and <a href="Andrei_Alexandrescu" title="Andrei Alexandrescu">Andrei Alexandrescu</a> (2005). <i>C++ Coding Standards</i>. p. 30. Boston: Addison Wesley. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <bdi>0-321-11358-6</bdi></span>
</li>
<li id="cite_note-5"><span class="mw-cite-backlink"><b><a href="#cite_ref-5">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://lkml.org/lkml/2013/1/12/139">"Why is the kfree() argument const?"</a>. lkml.org. 2013-01-12.</cite></span>
</li>
<li id="cite_note-6"><span class="mw-cite-backlink"><b><a href="#cite_ref-6">^</a></b></span> <span class="reference-text"><cite class="citation book cs1">"5.1. Extensions implemented in GNU Fortran: 5.1.16 Cray pointers". <a rel="nofollow" class="external text" href="https://gcc.gnu.org/onlinedocs/gfortran/Cray-pointers.html#Cray-pointers"><i>The GNU Fortran Compiler</i></a>. 2006. <a rel="nofollow" class="external text" href="https://web.archive.org/web/20221221175054/https://gcc.gnu.org/onlinedocs/gfortran/Cray-pointers.html#Cray-pointers">Archived</a> from the original on 2022-12-21<span class="reference-accessdate">. Retrieved <span class="nowrap">2022-12-21</span></span>.</cite></span>
</li>
<li id="cite_note-7"><span class="mw-cite-backlink"><b><a href="#cite_ref-7">^</a></b></span> <span class="reference-text"><cite id="CITEREFFaheyNagle1999" class="citation web cs1">Fahey, Mark R.; Nagle, Dan (1999-04-19). <a rel="nofollow" class="external text" href="https://fs.hlrs.de/projects/par/mooc/cray-pointers.pdf">"Cray Fortran Pointers vs. Fortran 90 Pointers and Porting from the Cray C90 to the SGI Origin2000"</a> <span class="cs1-format">(PDF)</span>. Vicksburg, Massachusetts, USA: US Army Corps of Engineers Waterways Experiment Station, Major Shared Resource Center. <a rel="nofollow" class="external text" href="https://web.archive.org/web/20221223105738/https://fs.hlrs.de/projects/par/mooc/cray-pointers.pdf">Archived</a> <span class="cs1-format">(PDF)</span> from the original on 2022-12-23<span class="reference-accessdate">. Retrieved <span class="nowrap">2022-12-23</span></span>.</cite> (8 pages)</span>
</li>
<li id="cite_note-8"><span class="mw-cite-backlink"><b><a href="#cite_ref-8">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://docs.oracle.com/cd/E19957-01/805-4941/z40000a54ba7/index.html">"Appendix C: Fortran 90 Features and Differences > Features > Cray Pointers"</a>. <i>Fortran User's Guide</i>. <a href="Oracle_Corporation" title="Oracle Corporation">Oracle Corporation</a>. 2010. <a rel="nofollow" class="external text" href="https://web.archive.org/web/20210921171349/https://docs.oracle.com/cd/E19957-01/805-4941/z40000a54ba7/index.html">Archived</a> from the original on 2021-09-21<span class="reference-accessdate">. Retrieved <span class="nowrap">2022-12-23</span></span>.</cite></span>
</li>
<li id="cite_note-9"><span class="mw-cite-backlink"><b><a href="#cite_ref-9">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://docs.oracle.com/cd/E19957-01/805-4941/z40000a5510b/index.html">"Appendix C: Fortran 90 Features and Differences > Features > Cray Character Pointers"</a>. <i>Fortran User's Guide</i>. <a href="Oracle_Corporation" title="Oracle Corporation">Oracle Corporation</a>. 2010. <a rel="nofollow" class="external text" href="https://web.archive.org/web/20221223112633/https://docs.oracle.com/cd/E19957-01/805-4941/z40000a5510b/index.html">Archived</a> from the original on 2022-12-23<span class="reference-accessdate">. Retrieved <span class="nowrap">2022-12-23</span></span>.</cite></span>
</li>
<li id="cite_note-10"><span class="mw-cite-backlink"><b><a href="#cite_ref-10">^</a></b></span> <span class="reference-text"><cite class="citation book cs1">"Chapter 4. Data Types". <a rel="nofollow" class="external text" href="https://techpubs.jurassic.nl/manuals/0630/developer/Ftn_LRM_V1/sgi_html/ch04.html"><i>Fortran Language Reference Manual, Volume 1</i></a>. Vol. 1. <a href="Silicon_Graphics%2C_Inc." class="mw-redirect" title="Silicon Graphics, Inc.">Silicon Graphics, Inc.</a> 1999 [1993]. Document Number: 007-3692-004. <a rel="nofollow" class="external text" href="https://web.archive.org/web/20221223110605/https://techpubs.jurassic.nl/manuals/0630/developer/Ftn_LRM_V1/sgi_html/ch04.html">Archived</a> from the original on 2022-12-23<span class="reference-accessdate">. Retrieved <span class="nowrap">2022-12-23</span></span>.</cite> (NB. Derived from "FORTRAN 90 HANDBOOK" (1992, <a href="McGraw-Hill%2C_Inc." class="mw-redirect" title="McGraw-Hill, Inc.">McGraw-Hill, Inc.</a>) by Walter S. Brainerd, Jeanne C. Adams, Jeanne T. Martin, Brian T. Smith, and Jerrold L. Wagener.)</span>
</li>
<li id="cite_note-11"><span class="mw-cite-backlink"><b><a href="#cite_ref-11">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://www.stroustrup.com/bs_faq2.html#whitespace">"Stroustrup: C++ Style and Technique FAQ"</a>.</cite></span>
</li>
<li id="cite_note-12"><span class="mw-cite-backlink"><b><a href="#cite_ref-12">^</a></b></span> <span class="reference-text"><a href="Scott_Meyers" title="Scott Meyers">Scott Meyers</a> (2005). <i>Effective C++, Third Edition</i>. pp. 21–23. Boston: Addison Wesley. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a> <bdi>978-0-321-33487-9</bdi></span>
</li>
<li id="cite_note-13"><span class="mw-cite-backlink"><b><a href="#cite_ref-13">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://msdn.microsoft.com/en-us/library/b34ccac3.aspx">"strchr, wcschr, _mbschr (CRT)"</a>. Msdn.microsoft.com<span class="reference-accessdate">. Retrieved <span class="nowrap">2017-11-23</span></span>.</cite></span>
</li>
<li id="cite_note-14"><span class="mw-cite-backlink"><b><a href="#cite_ref-14">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://www.lysator.liu.se/c/dmr-on-noalias.html">"Dennis Ritchie: Why I do not like X3J11 type qualifiers"</a>.</cite></span>
</li>
<li id="cite_note-d8_8-16"><span class="mw-cite-backlink">^ <a href="#cite_ref-d8_8_16-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-d8_8_16-1"><sup><i><b>b</b></i></sup></a></span> <span class="reference-text"><i>The D Programming Language,</i> <a href="Andrei_Alexandrescu" title="Andrei Alexandrescu">Andrei Alexandrescu</a>, 8.8: Propagating a Qualifier from Parameter to Result</span>
</li>
<li id="cite_note-N3020-19"><span class="mw-cite-backlink"><b><a href="#cite_ref-N3020_19-0">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3020.pdf">"WG14-N3020 : Qualifier-preserving standard library functions"</a> <span class="cs1-format">(PDF)</span>. <i>open-std.org</i>. 2022-06-13. <a rel="nofollow" class="external text" href="https://web.archive.org/web/20221013190826/https://www.open-std.org/jtc1/sc22/WG14/www/docs/n3020.pdf">Archived</a> <span class="cs1-format">(PDF)</span> from the original on 2022-10-13.</cite></span>
</li>
<li id="cite_note-20"><span class="mw-cite-backlink"><b><a href="#cite_ref-20">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://www.digitalmars.com/d/2.0/const-faq.html#const">"const(FAQ) – D Programming Language"</a>. Digitalmars.com<span class="reference-accessdate">. Retrieved <span class="nowrap">2013-08-18</span></span>.</cite></span>
</li>
<li id="cite_note-21"><span class="mw-cite-backlink"><b><a href="#cite_ref-21">^</a></b></span> <span class="reference-text"><a href="Bjarne_Stroustrup" title="Bjarne Stroustrup">Bjarne Stroustrup</a>, "Extensions of the C Language Type Concept", Bell Labs internal Technical Memorandum, January 5, 1981.</span>
</li>
<li id="cite_note-siblings-22"><span class="mw-cite-backlink">^ <a href="#cite_ref-siblings_22-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-siblings_22-1"><sup><i><b>b</b></i></sup></a> <a href="#cite_ref-siblings_22-2"><sup><i><b>c</b></i></sup></a></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://www.stroustrup.com/sibling_rivalry.pdf">Sibling Rivalry: C and C++</a>, <a href="Bjarne_Stroustrup" title="Bjarne Stroustrup">Bjarne Stroustrup</a>, 2002, p. 5</span>
</li>
<li id="cite_note-23"><span class="mw-cite-backlink"><b><a href="#cite_ref-23">^</a></b></span> <span class="reference-text"><a href="Dennis_M._Ritchie" class="mw-redirect" title="Dennis M. Ritchie">Dennis M. Ritchie</a>, "<a rel="nofollow" class="external text" href="http://cm.bell-labs.com/who/dmr/chist.html">The Development of the C Language</a> <a rel="nofollow" class="external text" href="https://archive.today/20120715050501/http://cm.bell-labs.com/who/dmr/chist.html">Archived</a> July 15, 2012, at <a href="Archive.today" title="Archive.today">archive.today</a>", 2003: "X3J11 also introduced a host of smaller additions and adjustments, for example, the type qualifiers <b>const</b> and <b>volatile</b>, and slightly different type promotion rules."</span>
</li>
<li id="cite_note-24"><span class="mw-cite-backlink"><b><a href="#cite_ref-24">^</a></b></span> <span class="reference-text">"Let me begin by saying that I'm not convinced that even the pre-December qualifiers ('const' and 'volatile') carry their weight; I suspect that what they add to the cost of learning and using the language is not repaid in greater expressiveness.
'Volatile', in particular, is a frill for esoteric applications, and much better expressed by other means. Its chief virtue is that nearly everyone can forget about it. 'Const' is simultaneously more useful and more obtrusive; you can't avoid learning about it, because of its presence in the library interface. Nevertheless, I don't argue for the extirpation of qualifiers, if only because it is too late."</span>
</li>
<li id="cite_note-26"><span class="mw-cite-backlink"><b><a href="#cite_ref-26">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://nim-lang.org/docs/manual.html#statements-and-expressions-const-section">Nim Manual: Const section</a></span>
</li>
<li id="cite_note-27"><span class="mw-cite-backlink"><b><a href="#cite_ref-27">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="https://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx">const (C# Reference)</a></span>
</li>
<li id="cite_note-28"><span class="mw-cite-backlink"><b><a href="#cite_ref-28">^</a></b></span> <span class="reference-text"><cite id="CITEREFGoslingJoySteele" class="citation web cs1">Gosling, James; Joy, Bill; Steele, Guy. <a rel="nofollow" class="external text" href="https://docs.oracle.com/javase/specs/jls/se6/html/lexical.html#3.9">"Java Language Specification Third Edition"</a>.</cite></span>
</li>
<li id="cite_note-29"><span class="mw-cite-backlink"><b><a href="#cite_ref-29">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://bugs.java.com/view_bug.do?bug_id=4211070">"Bug ID: JDK-4211070 Java should support const parameters (like C++) for code maintainence [<i>sic</i>]"</a>. Bugs.sun.com<span class="reference-accessdate">. Retrieved <span class="nowrap">2014-11-04</span></span>.</cite></span>
</li>
<li id="cite_note-30"><span class="mw-cite-backlink"><b><a href="#cite_ref-30">^</a></b></span> <span class="reference-text"><a rel="nofollow" class="external text" href="http://archive.adaic.com/standards/83lrm/html/Welcome.htmlANSI/MIL-STD">1815A</a>, <a rel="nofollow" class="external text" href="http://archive.adaic.com/standards/83lrm/html/lrm-03-02.html#3.2.1">3.2.1. Object Declarations</a> <a rel="nofollow" class="external text" href="https://web.archive.org/web/20141020162257/http://archive.adaic.com/standards/83lrm/html/lrm-03-02.html#3.2.1">Archived</a> October 20, 2014, at the <a href="Wayback_Machine" title="Wayback Machine">Wayback Machine</a>:<br>
"The declared object is a constant if the reserved word constant appears in the object declaration; the declaration must then include an explicit initialization. The value of a constant cannot be modified after initialization. Formal parameters of mode in of subprograms and entries, and generic formal parameters of mode in, are also constants; a loop parameter is a constant within the corresponding loop; a subcomponent or slice of a constant is a constant."</span>
</li>
<li id="cite_note-32"><span class="mw-cite-backlink"><b><a href="#cite_ref-32">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">"const"</a>. <i>MDN</i><span class="reference-accessdate">. Retrieved <span class="nowrap">2017-10-31</span></span>.</cite></span>
</li>
</ol></div></div>
<div class="mw-heading mw-heading2"><h2 id="External_links">External links</h2></div>
<ul><li><a rel="nofollow" class="external text" href="http://gotw.ca/gotw/006.htm">"Const-Correctness"</a> by <a href="Herb_Sutter" title="Herb Sutter">Herb Sutter</a></li>
<li><a rel="nofollow" class="external text" href="http://gotw.ca/gotw/081.htm">"Constant Optimization?"</a> by Herb Sutter</li>
<li><a rel="nofollow" class="external text" href="https://web.archive.org/web/20050611030410/http://www.parashift.com/c++-faq-lite/const-correctness.html">The C++ FAQ Lite: Const correctness</a> by Marshall Cline</li>
<li>Section "<a rel="nofollow" class="external text" href="http://www.mi.uni-koeln.de/c/mirror/www.codeguru.com/cpp/tic/tic_html.zip/tic0092.html">Value substitution</a>" from the free electronic book <i>Thinking in C++</i> by <a href="Bruce_Eckel" title="Bruce Eckel">Bruce Eckel</a></li>
<li><a rel="nofollow" class="external text" href="https://web.archive.org/web/20080105024742/http://www.digitalmars.com/d/const.html">"Here A Const, There A Const"</a> by <a href="Walter_Bright" title="Walter Bright">Walter Bright</a></li>
<li><a rel="nofollow" class="external text" href="http://www.digitalmars.com/d/2.0/const3.html">"Const and Invariant" from D programming language specification, version 2 (experimental)</a></li></ul></div><!--htdig_noindex--><div><div class="zim-footer">
This article is issued from <a class="external text" title="Last edited on 2025-07-29" href="https://en.wikipedia.org/wiki/?title=Const_(computer_programming)&oldid=1303148162">Wikipedia</a>. The text is available under <a class="external text" href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons Attribution-Share Alike 4.0</a> unless otherwise noted. Additional terms may apply for the media files.
</div>
</div><!--/htdig_noindex--></div>
</div>
</main>
</div>
</div>
</div>
</body></html>